package cn.com.yd.commons.grpc.config;

import cn.com.yd.commons.grpc.annotation.EnableStartGrpcClient;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnBean(annotation = EnableStartGrpcClient.class)
@EnableConfigurationProperties(GrpcClientProperties.class)
public class GrpcClientAutoConfiguration {
    @Autowired
    private GrpcClientProperties startGrpcClientProperties;

    @Bean
    public cn.com.yd.commons.grpc.GrpcClient create() {
        Integer maxTotal = startGrpcClientProperties.getMaxTotal();
        Boolean onBorrow = startGrpcClientProperties.getOnBorrow();
        Boolean onReturn = startGrpcClientProperties.getOnReturn();
        Boolean whileIdle = startGrpcClientProperties.getWhileIdle();
        Integer rate = startGrpcClientProperties.getRate();
        String server = startGrpcClientProperties.getServerIp();
        Integer port = startGrpcClientProperties.getPort();
        Boolean enabledSsl = startGrpcClientProperties.getEnabledSsl();

        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxWaitMillis(maxTotal * 1000L);
        if (null != onBorrow) {
            config.setTestOnBorrow(onBorrow);
        }
        if (null != onReturn) {
            config.setTestOnReturn(onReturn);
        }
        if (null != whileIdle) {
            config.setTestWhileIdle(whileIdle);
            if (whileIdle) {
                config.setTimeBetweenEvictionRunsMillis(rate * 1000L);
                config.setMinEvictableIdleTimeMillis(rate * 2 * 60000L);
            }
        }
        return new cn.com.yd.commons.grpc.GrpcClient(server, port, enabledSsl, config);
    }
}
